import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
import layui from "@/layout/index.vue";
import FilterRouteList from '@/service/FilterRouteList'

const routes: Array<RouteRecordRaw> = [
  {
    path: "/",
    name: "layui",
    component: layui,
    redirect: "/dashboard",
    children: [
      {
        path: "dashboard",
        component: () => import("@/views/dashboard/index.vue"),
        name: "Dashboard",
        meta: { title: "首页" },
      },
    ],
  },
  {
    path: "/login",
    name: "login",
    component: () => import("@/views/login/index.vue"),
  },
];
const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
});
let isF = false
// 全局守卫：登录拦截 本地没有存token,请重新登录
router.beforeEach((to, from, next) => {
  // 判断有没有登录
  if (!localStorage.getItem("ACCESS_TOKEN")) {
    if (to.name == "login") {
      next();
    } else {
      router.push("login");
      next()
    }
  } else {
    if (isF) {
      // console.log('缓存路由', isF);
      next();
    } else {
      let menus:any = localStorage.getItem('MENUS')
      menus = JSON.parse(menus)
      // 防止刷新页面空白，添加动态路由
      new FilterRouteList(menus)
      isF = true
      next({...to, replace: true});

    }
  }
});
export default router;
